//  配置路由
import Vue from 'vue'
import vueRouter from 'vue-router'

// 进行全局插件注册

Vue.use(vueRouter)

//引入路由组件

import Home from '@/pages/Home'
import Login from '@/pages/Login'
import Register from '@/pages/Register'
import Search from '@/pages/Search'

//原型上重写push  or  replace  方法
//1、先把vueRouter原型对象上的push方法保存一份
let originPush = vueRouter.prototype.push
// 2、重写push 方法
//第一个参数：告诉原来的push方法，往哪里跳转 ，第二，三个参数：成功和失败的回调
vueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(
      this,
      location,
      () => { },
      () => { }
    )
  }
}

// 重写 replace 方法
let originReplace = vueRouter.prototype.replace
vueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => { },
      () => { }
    )
  }
}

export default new vueRouter({
  routes: [
    {
      path: '/home',
      component: Home,
      meta: {
        show: true,
      },
    },
    {
      path: '/login',
      component: Login,
      meta: {
        show: false,
      },
    },

    {
      path: '/search/:keyword?',
      component: Search,
      meta: {
        show: true,
      },
      name: 'search',
      props: $route => ({
        keyword: $route.params.keyword,
        k: $route.query.k,
      }),
    },

    {
      path: '/register',
      component: Register,
      meta: {
        show: false,
      },
    },

    {
      // 配置重定向：项目跑起来的时候，访问/  ,立马让他定向到首页
      path: '/',
      redirect: '/home',
    },
  ],
})
